/** 一些简单的工具js（不牵扯到globalData或uni中的任何方法以及调用this）
 * @property {checkBgColor} 色值转透明度
 * @property {getCalendar} 获取当月的日历
 * @property {base64} base64转码
 * @property {getUrlPara} 获取URL中的指定参数
 * @property {compressImg} 图片压缩(base64压缩)
 * @property {change} 地图转换
 * @property {changeFileSize} 修改地图图片尺寸
 * @property {tabAutoScroll} tab切换使选中项自动居中
 * 需配合<scroll-vieww></scroll-vieww>使用
 * tabDom: tab切换的dom节点
 * index： 当点击项的index（不是选中项）
 * gapWidth：可视窗口宽度
 */
export default {
    checkBgColor(bgColor, opc) {
        opc = opc || opc === '0' ? opc : 100;
        let opacity = (opc / 100).toFixed(2);
        const alphaHexMap = { '1.00': 'FF', '0.99': 'FC', '0.98': 'FA', '0.97': 'F7', '0.96': 'F5', '0.95': 'F2', '0.94': 'F0', '0.93': 'ED', '0.92': 'EB', '0.91': 'E8', '0.90': 'E6', '0.89': 'E3', '0.88': 'E0', '0.87': 'DE', '0.86': 'DB', '0.85': 'D9', '0.84': 'D6', '0.83': 'D4', '0.82': 'D1', '0.81': 'CF', '0.80': 'CC', '0.79': 'C9', '0.78': 'C7', '0.77': 'C4', '0.76': 'C2', '0.75': 'BF', '0.74': 'BD', '0.73': 'BA', '0.72': 'B8', '0.71': 'B5', '0.70': 'B3', '0.69': 'B0', '0.68': 'AD', '0.67': 'AB', '0.66': 'A8', '0.65': 'A6', '0.64': 'A3', '0.63': 'A1', '0.62': '9E', '0.61': '9C', '0.60': '99', '0.59': '96', '0.58': '94', '0.57': '91', '0.56': '8F', '0.55': '8C', '0.54': '8A', '0.53': '87', '0.52': '85', '0.51': '82', '0.50': '80', '0.49': '7D', '0.48': '7A', '0.47': '78', '0.46': '75', '0.45': '73', '0.44': '70', '0.43': '6E', '0.42': '6B', '0.41': '69', '0.40': '66', '0.39': '63', '0.38': '61', '0.37': '5E', '0.36': '5C', '0.35': '59', '0.34': '57', '0.33': '54', '0.32': '52', '0.31': '4F', '0.30': '4D', '0.29': '4A', '0.28': '47', '0.27': '45', '0.26': '42', '0.25': '40', '0.24': '3D', '0.23': '3B', '0.22': '38', '0.21': '36', '0.20': '33', '0.19': '30', '0.18': '2E', '0.17': '2B', '0.16': '29', '0.15': '26', '0.14': '24', '0.13': '21', '0.12': '1F', '0.11': '1C', '0.10': '1A', '0.09': '17', '0.08': '14', '0.07': '12', '0.06': '0F', '0.05': '0D', '0.04': '0A', '0.03': '08', '0.02': '05', '0.01': '03', '0.00': '00', }

        let color = bgColor + alphaHexMap[opacity]; //转换之后的色值
        return color
    },
    getCalendar(year, month) {
        year = Number(year);
        month = Number(month);
        // 1.准备工作
        //  (1).每月总天数类型
        let monthType = {
            big: [1, 3, 5, 7, 8, 10, 12], //31天的月份
            normal: [4, 6, 9, 11], //30天的月份
            leap: [2], //29或28的月份
        };
        //  (2).是否是闰年
        let leapRule = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
        //  (3).当月的天数总数
        let dayCount = monthType.big.includes(month) ? 31 : monthType.normal.includes(month) ? 30 : leapRule ? 29 : 28;
        //  (4).当月第一天的星期几
        let weekDay = new Date(`${year}-${month}`).getDay();
        weekDay = weekDay == 0 ? 7 : weekDay;
        //  (5).日历数据（需要的）
        let calendar = [];
        // 2.逻辑处理
        let weekArr = []; //7天为一周，下标对应星期几，元素对应日期
        for (let i = 0; i < dayCount; i++) {
            weekArr[weekDay - 1] = i + 1;
            if (weekDay == 7) {
                //遇到周日重置
                weekDay = 1; //从周一开始
                calendar.push(weekArr); //保存到日历中
                weekArr = []; //重置周期标记
            } else if (dayCount - 1 == i) {
                //最后一周
                calendar.push(weekArr);
            } else {
                ++weekDay;
            }
        }
        return calendar;
    },
    base64(name, string) {
        let Base64 = {
            _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
            encode: function (e) {
                var t = "";
                var n, r, i, s, o, u, a;
                var f = 0;
                e = Base64._utf8_encode(e);
                while (f < e.length) {
                    n = e.charCodeAt(f++);
                    r = e.charCodeAt(f++);
                    i = e.charCodeAt(f++);
                    s = n >> 2;
                    o = (n & 3) << 4 | r >> 4;
                    u = (r & 15) << 2 | i >> 6;
                    a = i & 63;
                    if (isNaN(r)) {
                        u = a = 64
                    } else if (isNaN(i)) {
                        a = 64
                    }
                    t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this
                        ._keyStr.charAt(a)
                }
                return t
            },
            decode: function (e) {
                var t = "";
                var n, r, i;
                var s, o, u, a;
                var f = 0;
                e = e.replace(/[^A-Za-z0-9+/=]/g, "");
                while (f < e.length) {
                    s = this._keyStr.indexOf(e.charAt(f++));
                    o = this._keyStr.indexOf(e.charAt(f++));
                    u = this._keyStr.indexOf(e.charAt(f++));
                    a = this._keyStr.indexOf(e.charAt(f++));
                    n = s << 2 | o >> 4;
                    r = (o & 15) << 4 | u >> 2;
                    i = (u & 3) << 6 | a;
                    t = t + String.fromCharCode(n);
                    if (u != 64) {
                        t = t + String.fromCharCode(r)
                    }
                    if (a != 64) {
                        t = t + String.fromCharCode(i)
                    }
                }
                t = Base64._utf8_decode(t);
                return t
            },
            _utf8_encode: function (e) {
                e = e.replace(/rn/g, "n");
                var t = "";
                for (var n = 0; n < e.length; n++) {
                    var r = e.charCodeAt(n);
                    if (r < 128) {
                        t += String.fromCharCode(r)
                    } else if (r > 127 && r < 2048) {
                        t += String.fromCharCode(r >> 6 | 192);
                        t += String.fromCharCode(r & 63 | 128)
                    } else {
                        t += String.fromCharCode(r >> 12 | 224);
                        t += String.fromCharCode(r >> 6 & 63 | 128);
                        t += String.fromCharCode(r & 63 | 128)
                    }
                }
                return t
            },
            _utf8_decode: function (e) {
                var t = "";
                var n = 0;
                var r = c1 = c2 = 0;
                while (n < e.length) {
                    r = e.charCodeAt(n);
                    if (r < 128) {
                        t += String.fromCharCode(r);
                        n++
                    } else if (r > 191 && r < 224) {
                        c2 = e.charCodeAt(n + 1);
                        t += String.fromCharCode((r & 31) << 6 | c2 & 63);
                        n += 2
                    } else {
                        c2 = e.charCodeAt(n + 1);
                        c3 = e.charCodeAt(n + 2);
                        t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63);
                        n += 3
                    }
                }
                return t
            }
        }
        return Base64[name](string);
    },
    getUrlPara(url, name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = url.match(reg);
        if (r != null) return (r[2]);
        return null;
    },
    compressImg(initialBase64, callbackFn) {
        let targSize = 1024 * 1024 //1024KB  
        if (initialBase64.length <= targSize) { //小于1M不压缩
            callbackFn(initialBase64);
            return false
        }
        let img = document.createElement('img');
        let cvs = document.createElement('canvas');
        img.src = initialBase64;
        img.onload = function () {
            let ratio = img.naturalWidth / img.naturalHeight; //  获取原图比例,为了等比压缩
            cvs.width = 500;
            cvs.height = cvs.width / ratio;
            let ctx = cvs.getContext('2d');
            ctx.drawImage(img, 0, 0, cvs.width, cvs.height); //  画在 canvas 上
            // 压缩后新图的 base64
            let zipBase64 = cvs.toDataURL();
            img.remove(); //释放节点
            cvs.remove(); //释放节点
            callbackFn(zipBase64);
            return false
        }
    },
    change(lat, lng) {
        var x_pi = 3.14159265358979324 * 3000.0 / 180.0;
        var x = parseFloat(lng);
        var y = parseFloat(lat);
        var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
        var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);

        lng = z * Math.cos(theta) + 0.0065;
        lat = z * Math.sin(theta) + 0.006;
        var lnglat = lng + ',' + lat
        return lnglat;
    },
    changeFileSize(url, width, height) {
        if (url == '' || url == undefined) {
            return '';
        }

        //小图尺寸
        if (width == 'small') {
            width = 200;
            height = 200;
        }

        //中图尺寸
        if (width == 'middle') {
            width = 500;
            height = 500;
        }

        //默认尺寸
        width = typeof width === 'number' ? width : 800;
        height = typeof height === 'number' ? height : 800;

        //阿里云、华为云
        url = url.replace('w_4096', 'w_' + width);
        url = url.replace('h_4096', 'h_' + height);

        //七牛云
        url = url.replace('w/4096', 'w/' + width);
        url = url.replace('h/4096', 'h/' + height);

        //腾讯云
        url = url.replace('4096x4096', width + 'x' + height);
        return url;
    },
    tabAutoScroll(tabDom, index, gapWidth) {
        let scrollLeft = 0; //相对于未滚动时的滚动的距离（即滚动条的位置）
        let currentDom = tabDom[index]; ///点击项信息
        let lastDom = tabDom[tabDom.length - 1]; //最后项信息
        let plusDis = currentDom.left + currentDom.width; //点击项左侧距离+宽度
        let minusDis = lastDom.left + lastDom.width + lastDom.right - currentDom.left; //剩余可滚动距离
        if (minusDis <= gapWidth / 2) {
            //直接拉到最右侧
            scrollLeft = minusDis + currentDom.left;
        } else if (plusDis > gapWidth / 2) {
            //点击项与可视窗口左且右侧间距超过一半，居中处理
            // 点击项与最左侧（也就是第一个元素）的距离，减去可视窗口一半的距离就是滚动条要移动的距离，即居中
            scrollLeft = plusDis - currentDom.width / 2 - gapWidth / 2;
        } else {
            //不满足居中的，直接拉到左侧(因为滚动条是向右滚动的，所以不考虑直接拉到右侧的情况)
            scrollLeft = 0;
        }
        return scrollLeft;
    },
};